<template>
  <div>
    <el-dialog
      :title="info.isAdd ? '商品添加' : '商品编辑'"
      :visible.sync="info.isshow"
      @close="close"
      @opened="opened"
    >
      <el-form :model="user">
        <el-form-item label="一级分类" label-width="120px">
          <el-select v-model="user.first_cateid" @change="change_first_cate">
            <el-option
              v-for="item in cateList"
              :key="item.id"
              :label="item.catename"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="二级分类" label-width="120px">
          <el-select v-model="user.second_cateid">
            <el-option
              v-for="item in second_cate_list"
              :key="item.id"
              :label="item.catename"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="商品名称" label-width="120px">
          <el-input v-model="user.goodsname"></el-input>
        </el-form-item>

        <el-form-item label="价格" label-width="120px">
          <el-input v-model="user.price"></el-input>
        </el-form-item>

        <el-form-item label="市场价格" label-width="120px">
          <el-input v-model="user.market_price"></el-input>
        </el-form-item>

        <el-form-item label="图片" label-width="120px">
          <!-- 6.处理图片 -->
          <upload-img @sendFile="user.img = $event" ref="upload"></upload-img>
        </el-form-item>
        <div>{{ user }}</div>
        <div>{{ attrsArr }}</div>

        <el-form-item label="商品规格" label-width="120px">
          <el-select v-model="user.specsid" @change="change_specs_id">
            <el-option
              v-for="item in specsList"
              :key="item.id"
              :label="item.specsname"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="规格属性" label-width="120px">
          <el-select v-model="user.specsattr" multiple>
            <el-option
              v-for="item in attr_arr"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="是否新品" label-width="120px">
          <el-radio v-model="user.isnew" :label="1">是</el-radio>
          <el-radio v-model="user.isnew" :label="2">否</el-radio>
        </el-form-item>

        <el-form-item label="是否热卖" label-width="120px">
          <el-radio v-model="user.ishot" :label="1">是</el-radio>
          <el-radio v-model="user.ishot" :label="2">否</el-radio>
        </el-form-item>

        <el-form-item label="状态" label-width="120px">
          <el-switch
            v-model="user.status"
            :active-value="1"
            :inactive-value="2"
          >
          </el-switch>
        </el-form-item>

        <el-form-item label="商品描述" label-width="120px">
          <div id="editor" v-if="info.isshow"></div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dia log-footer">
        <el-button type="primary" v-if="info.isAdd" @click="add"
          >添 加</el-button
        >
        <el-button type="primary" v-else @click="update">修 改</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { mapGetters, mapActions } from "vuex";
import { reqgoodsedit, reqgoodsadd, reqgoodsinfo } from "../../../http/api";
import { successAlert } from "../../../utils/alert";
import { formClose } from "../../../minxins/index";
import { reqcatelist } from "../../../../../../day14/code/u_back/src/http/api";
import E from "wangeditor";

export default {
  // 接收info
  props: ["info"],
  mixins: [formClose],
  data() {
    return {
      // 1初始化表单的数据
      user: {
        first_cateid: "",
        second_cateid: "",
        goodsname: "",
        price: "",
        market_price: "",
        img: null,
        description: "",
        specsid: "",
        specsattr: "",
        isnew: 2,
        ishot: 2,
        status: 1,
      },
      // 二级分类的列表
      second_cate_list: [],
      // 规格属性的列表
      attr_arr: [],

      attrsArr: [
        {
          val: "",
        },
        {
          val: "",
        },
      ],
    };
  },
  computed: {
    ...mapGetters({
      // 2.取出一级分类的列表
      cateList: "cate/arr",
      // 7.取出商品规格的列表
      specsList: "specs/arr",
    }),
  },
  mounted() {
    // 4.请求分类数据
    this.reqCateArr();
    // 9.请求规格
    this.reqSpecsList(true);
  },
  methods: {
    ...mapActions({
      // 3.请求分类的方法
      reqCateArr: "cate/reqArr",
      // 8.去除请求商品规格的方法
      reqSpecsList: "specs/reqList",
      // 商品请求
      reqArr: "goods/reqArr",
    }),

    //  弹框打开完成，我们要创建编辑器
    opened() {
      // 创建编辑器
      const editor = new E("#editor");
      editor.create();

      this.editor.txt.html(this.user.description); // 重新设置编辑器内容
    },

    //  5.选了一级分类
    change_first_cate() {
      // 清空二级分类选中的值
      this.user.second_cateid = "";
      // 根据一级分类取出其下面的二级分类列表
      this.get_second_cate_list();
    },
    // 根据一级分类取出其下面的二级分类列表
    get_second_cate_list() {
      reqcatelist({ pid: this.user.first_cateid }).then((res) => {
        if (res.data.code == 200) {
          this.second_cate_list = res.data.list;
        }
      });
    },

    // 9.修改了商品规格
    change_specs_id() {
      // 选中的规格属性清空
      this.user.specsattr = [];
      // 展示规格属性的列表
      this.get_specs_attrs();
    },
    // 获取规格属性的列表
    get_specs_attrs() {
      // 规格列表里找 哪条数据的id===这user的规格的id
      let obj = this.specsList.find((item) => item.id == this.user.specsid); //{} undefind
      // 展示的规格属性列表
      this.attr_arr = obj ? obj.attrs : [];
    },

    // 清空弹窗的方法
    clearUser() {
      this.user = {
        first_cateid: "",
        second_cateid: "",
        goodsname: "",
        price: "",
        market_price: "",
        img: null,
        description: "",
        specsid: "",
        specsattr: "",
        isnew: 2,
        ishot: 2,
        status: 1,
      };
      // 二级分类的列表
      this.second_cate_list = [];
      // 规格属性的列表
      this.attr_arr = [];
      //清除图片
      this.$refs.upload.setImgUrl("");
    },

    // 5.4点了添加按钮
    add() {
      // 处理attrs
      reqgoodsadd({
        ...this.user,
        specsattr: this.user.specsattr.join(","),
         description: this.editor.txt.html(), //富文本编辑器的内容赋值给description
      }).then((res) => {
        if (res.data.code == 200) {
          // （1）弹成功
          successAlert(res.data.msg);
          // （2）清空弹窗
          this.clearUser();
          // （3）关闭弹窗
          this.info.isshow = false;
          // （4）添加一条数据，重新请求列表
          // this.$emit("init");
          this.reqArr();
        }
      });
    },
    // 6.6上级菜单发生了改变
    changepid() {
      //  如果上级菜单时 顶级菜单， 那么类型就是目录， 否则，类型就是菜单
      if (this.user.pid == 0) {
        this.user.type = 1;
      } else {
        this.user.type = 2;
      }
    },
    // 8.编辑逻辑
    getOne(id) {
      // console.log("发请求"+id);
      reqgoodsinfo({ id: id }).then((res) => {
        if (res.data.code == 200) {
          this.user = res.data.list;
          // 补id
          this.user.id = id;
          // 根据一级分类取出其下面的二级分类列表
          this.get_second_cate_list();
          // 给图片赋值
          this.$refs.upload.setImgUrl(this.$pre + this.user.img);
          // 处理规格属性
          this.user.specsattr = this.user.specsattr.split(",");
          // 获取规格属性的列表

          // 如果编辑器创建好了，再给编辑器赋值
          this.get_specs_attrs();
            if (this.editor) {
            this.editor.txt.html(this.user.description); // 重新设置编辑器内容
          }
        }
      });
    },
    // 9.点击修改
    update() {
      reqgoodsedit({
        ...this.user,
        specsattr: this.user.specsattr.join(","),
      }).then((res) => {
        if (res.data.code == 200) {
          // ①弹成功
          successAlert(res.data.msg);
          // ②弹框内容清空
          this.clearUser();
          // ③弹框消失
          this.info.isshow = false;
          // ④重新请求列表
          // this.$emit("init");
          this.reqArr();
        }
      });
    },
  },
};
</script>
<style scoped lang="less">
@import "../../../less/index.less";
.iptandbtn {
  display: flex;
  .el-button {
    width: auto;
  }
  .el-input {
    flex: 1;
  }
}
</style>